﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace TA.Turbo
{
	/// <summary>
	/// For a list of control IDs, adds a way to add and remove controls to an instance of List&lt;T&gt;.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class MultiControlValue<T> : MultiPartValue
		where T : Control
	{
		#region PUBLIC
		/// <summary>
		/// Ctor.
		/// </summary>
		/// <param name="owner">The starting point used when finding controls by their ids.</param>
		public MultiControlValue(Control owner)
		{
			this._owner = owner;
		}
		#region PROPS
		/// <summary>
		/// Collection of controls.
		/// </summary>
		public List<T> ControlList
		{
			get
			{
				if (this._controls == null)
				{
					this._controls = new List<T>();
					string[] controlIds = (this._value ?? "").Split(this.Separators, StringSplitOptions.RemoveEmptyEntries);
					foreach (string oneControlId in controlIds)
						this._controls.Add(this._owner.FindControlGlobal(oneControlId) as T);
				}
				return this._controls;
			}
		}
		/// <summary>
		/// Comma-separated list of control IDs.
		/// </summary>
		public override string Value
		{
			get
			{
				if (_controls != null)
				{
					StringBuilder sb = new StringBuilder();
					foreach (T oneControl in this._controls)
					{
						if (sb.Length > 0) sb.Append(Separators[0]);

						string id = oneControl.GetRelativeId(this._owner);
						if (id == null)
							id = oneControl.UniqueID;

						sb.Append(id);
					}
					_value = sb.ToString();

					NullifyLists();
				}
				return base.Value;
			}
			set
			{
				base.Value = value;
			}
		}
		#endregion
		#endregion
		#region INTERNAL
		#region VARS
		List<T> _controls;
		Control _owner;
		#endregion
		#region METHODS
		/// <summary>
		/// Nullifies the control list variable.
		/// </summary>
		protected override void NullifyLists()
		{
			base.NullifyLists();
			_controls = null;
		}
		#endregion
		#endregion
	}
}